const express = require('express');
const router = express.Router();
const Payment = require('../models/Payment');
const Post = require('../models/Post');
const auth = require('../middleware/auth');

// 调试中间件
router.use((req, res, next) => {
  console.log('💰 Payments route:', req.method, req.url);
  next();
});

// 创建支付（寄养人支付）
router.post('/', auth, async (req, res) => {
  try {
    const { postId, amount, paymentMethod } = req.body;
    console.log('💳 Creating payment - User:', req.userId, 'Post:', postId);
    
    // 检查帖子是否存在且有效
    const post = await Post.findById(postId)
      .populate('author')
      .populate('fosterUser');
      
    if (!post) {
      return res.status(404).json({ error: '帖子不存在' });
    }
    
    // 检查权限：只有帖子作者（寄养人）可以支付
    if (post.author._id.toString() !== req.userId.toString()) {
      return res.status(403).json({ error: '只有寄养人可以支付' });
    }
    
    // 检查帖子状态
    if (post.status !== 'in_progress') {
      return res.status(400).json({ error: '帖子不在可支付状态' });
    }
    
    // 检查金额
    if (amount !== post.price) {
      return res.status(400).json({ error: '支付金额不正确' });
    }

    // 计算平台服务费和实际给收养人的金额（假设平台收取10%服务费）
    const platformFee = amount * 0.1;
    const fosterAmount = amount - platformFee;

    const payment = new Payment({
      userId: req.userId, // 支付人（寄养人）
      postId: postId,
      amount: amount,
      paymentMethod: paymentMethod,
      status: 'pending',
      type: 'foster_payment',
      fosterUserId: post.fosterUser._id, // 收养人
      platformFee: platformFee,
      fosterAmount: fosterAmount
    });
    
    await payment.save();
    
    console.log('✅ Payment created:', payment._id);
    
    // 模拟支付成功
    setTimeout(async () => {
      try {
        payment.status = 'completed';
        payment.transactionId = 'TX' + Date.now();
        await payment.save();
        
        // 支付成功后更新帖子状态
        await Post.findByIdAndUpdate(postId, {
          status: 'paid',
          paymentId: payment._id
        });
        
        console.log('✅ Payment completed and post status updated');
      } catch (error) {
        console.error('❌ Payment completion error:', error);
      }
    }, 2000);

    res.json(payment);
  } catch (error) {
    console.error('❌ Create payment error:', error);
    res.status(500).json({ error: '创建支付失败' });
  }
});

// 获取支付历史
router.get('/history', auth, async (req, res) => {
  try {
    console.log('📋 Getting payment history for user:', req.userId);
    
    const payments = await Payment.find({ 
      $or: [
        { userId: req.userId },  // 作为支付人（寄养人）
        { fosterUserId: req.userId } // 作为收款人（收养人）
      ]
    })
    .populate('postId', 'title')
    .populate('userId', 'username') // 支付人（寄养人）
    .populate('fosterUserId', 'username') // 收款人（收养人）
    .sort({ createdAt: -1 });
    
    console.log(`✅ Found ${payments.length} payment records`);
    res.json(payments);
  } catch (error) {
    console.error('❌ Get payment history error:', error);
    res.status(500).json({ error: '获取支付历史失败' });
  }
});

// 获取收款记录（收养人）
router.get('/income', auth, async (req, res) => {
  try {
    console.log('💰 Getting income for user:', req.userId);
    
    const payments = await Payment.find({ 
      fosterUserId: req.userId,
      status: 'completed'
    })
    .populate('postId', 'title')
    .populate('userId', 'username') // 支付人（寄养人）
    .sort({ createdAt: -1 });
    
    // 计算总收入
    const totalIncome = payments.reduce((sum, payment) => sum + payment.fosterAmount, 0);
    
    console.log(`✅ Found ${payments.length} income records, total: ${totalIncome}`);
    res.json({
      payments,
      totalIncome
    });
  } catch (error) {
    console.error('❌ Get income error:', error);
    res.status(500).json({ error: '获取收款记录失败' });
  }
});

module.exports = router;